package com.unSafe;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

// ConcurrentModificationException:并发修改异常
public class MapTest {
    public static void main(String[] args) {
//        Map<String, Object> map = new HashMap<>();
        // 初始化容量、加载因子
//        Map<String, Object> map = new HashMap<String, Object>(16);

        // 解决方案一：利用工具类转换成 synchronized
//        Map<String, Object> map = Collections.synchronizedMap(new HashMap<>());
        // 解决方案二：ConcurrentHashMap
        Map<String, Object> map = new ConcurrentHashMap<>();
        // public ConcurrentHashMap(int initialCapacity) {
        //        if (initialCapacity < 0)
        //            throw new IllegalArgumentException();
        //        int cap = ((initialCapacity >= (MAXIMUM_CAPACITY >>> 1)) ?
        //                   MAXIMUM_CAPACITY :
        //                   tableSizeFor(initialCapacity + (initialCapacity >>> 1) + 1));
        //        this.sizeCtl = cap;
        //    }
        for (int i = 1; i <= 10; i++) {
            new Thread(() -> {
                map.put(Thread.currentThread().getName(), UUID.randomUUID().toString().substring(0, 5));
                System.out.println(map);
            }, String.valueOf(i)).start();
        }
    }
}
